var React = require('react');
var ListStore = require('../stores/ListStore');
var MyButton = require('./MyButton');
var ButtonActions = require('../actions/ButtonActions');

// 该组件实现的控制器操作(controller)
var MyButtonController = React.createClass({
	getInitialState:function(){
		return {
			items:ListStore.getAll()
		}
	},

	componentDidMount:function(){
		ListStore.addChangeListener(this._onChange);
	},
	componentWillUnmount:function(){
		ListStore.removeChangeListener(this._onChange);
	},

	_onChange:function(){
		console.log('_onChange');
		this.setState({
			items:ListStore.getAll()
		})
	},

	removeItem:function(e){
		var index = e.target.dataset.index;
		ButtonActions.removeItem(index); // Action -> dispatcher -> stroe -> view -> EventListener -> _onChange -> ListStore.getAll()
	},

	addNewItem:function(e){
		if(e.keyCode == 13){
			var value = e.target.value;
			ButtonActions.addNewItem(value);
			e.target.value = "";
		}
	},

	createNewItem:function(e){
		// this.state.items.push('new items');
		// this.setState({
		// 	items:this.state.items
		// })
		ButtonActions.addNewItem('new item');
	},

	render:function(){
		return (
			<MyButton items={this.state.items} onEnterHandle={this.addNewItem} onRemoveItemHandle={this.removeItem} onClick={this.createNewItem}/>
		)
	}
})

module.exports = MyButtonController;